package cn.highedu.coolshark.account.security;

import cn.highedu.coolshark.account.security.UserDetailsImpl;
import cn.highedu.coolshark.account.service.IAdminService;
import cn.highedu.coolshark.account.pojo.vo.AdminLoginInfoVO;
import cn.highedu.coolshark.account.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Spring Security处理认证时使用到的获取管理员登录详情的实现类
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IAdminService adminService;

    /**
     * 根据用户名获取登录信息
     * @param username 用户名
     * @return 登录信息
     * @throws UsernameNotFoundException 用户名不存在
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("Spring Security自动调用了loadUserByUsername()方法，参数：{}", username);
        AdminLoginInfoVO loginInfo = adminService.getAdminLoginInfo(username);
        if (loginInfo != null) {
            return new UserDetailsImpl(loginInfo);
        }
        throw new UsernameNotFoundException("用户名不存在");
    }

}
